<template>
  <div class="register-container">
    <NavBar>
      <template #default> 注册 </template>
    </NavBar>

    <div class="register-content">
      <div class="logo">
        <el-icon color="#ff5000" :size="60">
          <ShoppingTrolley />
        </el-icon>
      </div>

      <div class="register-form">
        <!-- 头像上传 -->
        <div class="avatar-container">
          <el-upload
            class="avatar-uploader"
            :show-file-list="false"
            :before-upload="beforeAvatarUpload"
            action="#"
            :auto-upload="false"
            :on-change="handleAvatarChange"
          >
            <img v-if="avatarUrl" :src="avatarUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon">
              <Plus />
            </el-icon>
          </el-upload>
          <div class="avatar-tip">点击上传头像（可选）</div>
        </div>

        <!-- 用户名 -->
        <div class="input-container">
          <el-input
            v-model="formData.userName"
            placeholder="请输入用户名"
            class="custom-input"
            :prefix-icon="User"
            clearable
          />
        </div>

        <!-- 手机号 -->
        <div class="input-container">
          <el-input
            v-model="formData.phone"
            placeholder="请输入手机号"
            class="custom-input"
            :prefix-icon="Iphone"
            clearable
          />
        </div>

        <!-- 邮箱 -->
        <div class="input-container">
          <el-input
            v-model="formData.email"
            placeholder="请输入邮箱"
            class="custom-input"
            :prefix-icon="Message"
            clearable
          />
        </div>

        <!-- 性别 -->
        <div class="input-container">
          <el-select
            v-model="formData.gender"
            placeholder="请选择性别"
            class="custom-select"
          >
            <el-option label="男" value= 1 />
            <el-option label="女" value= 2 />
            <el-option label="保密" value= 0 />
          </el-select>
        </div>

        <!-- 密码 -->
        <div class="input-container">
          <el-input
            v-model="formData.password"
            placeholder="请输入密码"
            type="password"
            class="custom-input"
            :prefix-icon="Lock"
            show-password
            clearable
          />
        </div>

        <!-- 确认密码 -->
        <div class="input-container">
          <el-input
            v-model="formData.confirmPassword"
            placeholder="请确认密码"
            type="password"
            class="custom-input"
            :prefix-icon="Lock"
            show-password
            clearable
          />
        </div>

        <el-button
          class="register-btn"
          type="primary"
          @click="handleRegister"
          :loading="isRegistering"
        >
          注册
        </el-button>
        <br />
        <br />
        <el-button class="login-btn" @click="goToLogin">
          已有账号？去登录
        </el-button>
      </div>
    </div>

    <div class="bottom-cover">
      <div class="bottom-links">
        <span @click="goToAbout">关于</span>
        <span class="divider">|</span>
        <span @click="goToPrivacy">隐私政策</span>
      </div>
    </div>
  </div>
</template>

<script setup>
import NavBar from "../../components/common/NavBar.vue";
import { ref, reactive } from "vue";
import {
  ShoppingTrolley,
  User,
  Lock,
  Iphone,
  Message,
  Plus
} from "@element-plus/icons-vue";
import router from "@/router";
import { ElMessage } from "element-plus";
import { UserRegister } from '@/api/UserApi';

// 导入 Pinia user store (如果需要)
// import { useUserStore } from "@/stores/user";

// 表单数据
const formData = reactive({
  userName: "牢弟",
  phone: "18827345432",
  email: "8374563@qq.com",
  password: "123123",
  confirmPassword: "123123",
  gender: 1,
  avatarFile: null, // 头像文件
});

const avatarUrl = ref(""); // 头像预览URL
const isRegistering = ref(false); // 注册按钮加载状态

// 获取 user store 实例 (如果需要)
// const userStore = useUserStore();

/**
 * 头像上传前的校验
 */
const beforeAvatarUpload = (file) => {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isJPG) {
    ElMessage.error('头像图片只能是 JPG/PNG 格式!');
  }
  if (!isLt2M) {
    ElMessage.error('头像图片大小不能超过 2MB!');
  }
  return isJPG && isLt2M;
};

/**
 * 头像文件改变时的处理
 */
const handleAvatarChange = (file) => {
  // 只保存文件对象和本地预览URL，不上传
  formData.avatarFile = file.raw;
  avatarUrl.value = URL.createObjectURL(file.raw);
};

/**
 * 表单验证
 */
const validateForm = () => {
  if (!formData.userName.trim()) {
    ElMessage.warning("请输入用户名！");
    return false;
  }

  if (!formData.phone.trim()) {
    ElMessage.warning("请输入手机号！");
    return false;
  }

  // 手机号格式验证
  const phoneRegex = /^1[3-9]\d{9}$/;
  if (!phoneRegex.test(formData.phone)) {
    ElMessage.warning("请输入正确的手机号格式！");
    return false;
  }

  if (!formData.email.trim()) {
    ElMessage.warning("请输入邮箱！");
    return false;
  }

  // 邮箱格式验证
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  if (!emailRegex.test(formData.email)) {
    ElMessage.warning("请输入正确的邮箱格式！");
    return false;
  }

  if (!formData.gender) {
    ElMessage.warning("请选择性别！");
    return false;
  }

  if (!formData.password.trim()) {
    ElMessage.warning("请输入密码！");
    return false;
  }

  if (formData.password.length < 6) {
    ElMessage.warning("密码长度不能少于6位！");
    return false;
  }

  if (!formData.confirmPassword.trim()) {
    ElMessage.warning("请确认密码！");
    return false;
  }

  if (formData.password !== formData.confirmPassword) {
    ElMessage.warning("两次输入的密码不一致！");
    return false;
  }

  return true;
};

/**
 * 处理注册逻辑
 */
const handleRegister = async () => {
  // 1. 表单验证
  if (!validateForm()) {
    return;
  }

  isRegistering.value = true; // 开始注册，设置加载状态



  try {
    // 2. 构建注册数据
    const registerData = new FormData();
    registerData.append('userName', formData.userName);
    registerData.append('mobile', formData.phone);
    registerData.append('email', formData.email);
    registerData.append('userPassword', formData.password);
    registerData.append('gender', formData.gender);
    if (formData.avatarFile) {
        registerData.append('avatarFile', formData.avatarFile);
    }

    // 3. 调用注册API (这里需要根据实际后端API进行调用)
    // await userStore.register(registerData);
    // 或者直接调用API
    const response = await UserRegister(registerData);
    console.log('这是register注册返回的数据：' + response);
    console.log(response);

    // 4. 注册成功处理
    if (response.data.code === 1) {
      ElMessage.success("注册成功！请登录");
      router.push("/login");
    } else {
      ElMessage.error(response.msg || '注册失败');
    }
  } catch (error) {
    // 5. 处理注册失败
    const errorMessage =
      error.message ||
      error.response?.data?.message ||
      "注册失败，请稍后重试。";
    ElMessage.error(errorMessage);
  } finally {
    // 重置加载状态
    isRegistering.value = false;
  }
};

/**
 * 跳转到登录页面
 */
const goToLogin = () => {
  router.push("/login");
};

/**
 * 跳转到关于页面
 */
const goToAbout = () => {
  router.push("/about");
};

/**
 * 跳转到隐私政策页面
 */
const goToPrivacy = () => {
  router.push("/privacy");
};
</script>

<style scoped>
.register-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: white;
  overflow-y: auto; /* 允许滚动，因为注册表单较长 */
}

.register-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px;
  margin-top: 20px;
  min-height: calc(100vh - 200px); /* 确保内容区域有足够高度 */
}

.logo {
  margin-bottom: 30px;
  display: flex;
  justify-content: center;
}

.register-form {
  width: 100%;
  max-width: 300px;
}

/* 头像上传样式 */
.avatar-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 20px;
}

.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 50%;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 80px;
  height: 80px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.avatar-uploader:hover {
  border-color: #ff5000;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
}

.avatar {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  object-fit: cover;
}

.avatar-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 8px;
  text-align: center;
}

.input-container {
  margin-bottom: 15px; /* 减少间距以适应更多字段 */
}

/* 统一输入框样式 */
:deep(.custom-input .el-input__wrapper) {
  border-radius: 25px;
  padding: 0 20px;
  height: 45px; /* 稍微减小高度 */
  box-shadow: 0 0 0 1px #dcdfe6 inset;
}

:deep(.custom-input .el-input__wrapper:hover) {
  box-shadow: 0 0 0 1px #c0c4cc inset;
}

:deep(.custom-input .el-input__wrapper.is-focus) {
  box-shadow: 0 0 0 1px #ff5000 inset;
}

:deep(.custom-input .el-input__inner) {
  height: 43px;
}

/* 下拉选择框样式 */
:deep(.custom-select .el-select__wrapper) {
  border-radius: 25px;
  padding: 0 20px;
  height: 45px;
  box-shadow: 0 0 0 1px #dcdfe6 inset;
}

:deep(.custom-select .el-select__wrapper:hover) {
  box-shadow: 0 0 0 1px #c0c4cc inset;
}

:deep(.custom-select .el-select__wrapper.is-focused) {
  box-shadow: 0 0 0 1px #ff5000 inset;
}

.custom-select {
  width: 100%;
}

/* 注册按钮样式 */
.register-btn {
  width: 100%;
  height: 45px;
  border-radius: 25px;
  background-color: #ff5000;
  border: none;
  font-size: 16px;
  font-weight: bold;
  margin-top: 10px;
}

.register-btn:hover {
  background-color: #ff3a00;
}

.login-btn {
  width: 100%;
  height: 45px;
  border-radius: 25px;
  background-color: #ffffff;
  border: none;
  font-size: 16px;
  font-weight: bold;
  border: 1px solid #000000;
}

.login-btn:hover {
  color: #3b3b3b;
  background-color: #f5f5f5;
}

/* 覆盖底部导航栏 */
.bottom-cover {
  height: 120px; /* 减小高度 */
  background-color: white;
  z-index: 1000;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  justify-content: center;
  align-items: center;
  padding-bottom: 20px;
}

.bottom-links {
  display: flex;
  align-items: center;
  font-size: 14px;
}

.bottom-links span {
  cursor: pointer;
  color: #606266;
  transition: color 0.3s;
}

.bottom-links span:hover {
  color: #ff5000;
}

.bottom-links .divider {
  margin: 0 10px;
  color: #dcdfe6;
  cursor: default;
}

/* 响应式设计 */
@media (max-height: 800px) {
  .register-content {
    padding: 15px;
    margin-top: 10px;
  }

  .logo {
    margin-bottom: 20px;
  }

  .input-container {
    margin-bottom: 12px;
  }

  .avatar-container {
    margin-bottom: 15px;
  }
}</style>